package edu.langnan.xiaoli.utils.file;

import edu.langnan.xiaoli.exception.file.FileImageInvalidExtensionException;
import edu.langnan.xiaoli.exception.file.FileSizeLimitExceededException;
import edu.langnan.xiaoli.utils.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author cql
 */
public class FileUploadUtils {

    private static final Logger log = LoggerFactory.getLogger(FileUploadUtils.class);


    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 10 * 1024 * 1024;

    /**
     * 默认的文件名最大长度 50
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 50;

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @return
     */
    public static final void assertAllowed(MultipartFile file, String[] allowedExtension) {
        long size = file.getSize();
        String fileName = file.getOriginalFilename();
        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) {
            log.error("{} 文件大小不合适", fileName);
            throw new FileSizeLimitExceededException();
        }
        if (fileName == "" || fileName.length() > DEFAULT_FILE_NAME_LENGTH) {
            log.error("{} 文件文件名长度不合适", fileName);
            throw new FileSizeLimitExceededException();
        }
        String extension = getExtension(file);
        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
            log.error("{} 文件格式不正确", fileName);
            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
                throw new FileImageInvalidExtensionException();
            }
        }

    }


    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension
     * @param allowedExtension
     * @return
     */
    public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }

}
